/*
 * Copyright 2010 Mttang.com All right reserved. This software is the confidential and proprietary information of
 * Mttang.com ("Confidential Information"). You shall not disclose such Confidential Information and shall use it only
 * in accordance with the terms of the license agreement you entered into with Mttang.com.
 */
package com.mttang.sys.web.controller;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.MessageSource;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import com.mttang.framework.core.paginated.util.PagedFliper;
import com.mttang.framework.core.paginated.util.Sheet;
import com.mttang.framework.core.paginated.web.controller.AbstractController;
import com.mttang.framework.core.paginated.web.dto.PagedDataModel;
import com.mttang.sys.biz.action.RoleAction;
import com.mttang.util.InfoAppKeyConstant;

/**
 * 类RoleActionController.java的实现描述：角色的操作 TODO 类实现描述
 * 
 * @author
 */
public class RoleActionController extends AbstractController {

	private RoleAction roleAction;

	public void setRoleAction(RoleAction roleAction) {
		this.roleAction = roleAction;
	}

	/**
	 * 角色查询
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView query(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		MessageSource msg = (MessageSource) this.getApplicationContext()
				.getBean("messageSource");

		try {
			if (logger.isInfoEnabled()) {
				logger.info("调用远程接口: roleAction");
			}
			Map<String, Object> condition = new HashMap<String, Object>();
			Map<String, Object> map = new HashMap<String, Object>();
			if (request.getParameter("roleName") != null
					&& !request.getParameter("roleName").equals("")) {

				String roleName = request.getParameter("roleName").trim();
				roleName = roleName.replace("%", "\\%");
				roleName = roleName.replace("_", "\\_");
				map.put("roleName", roleName);
				request.setAttribute("roleName",
						request.getParameter("roleName"));
			}

			String message = request.getParameter("message");
			if ("1".equals(message)) {
				message = msg.getMessage("sys.ok", null, Locale.CHINA);
			} else if ("2".equals(message)) {
				message = msg.getMessage("sys.role.in", null, Locale.CHINA);
			} else if ("3".equals(message)) {
				message = msg.getMessage("sys.roleuser.error", null,
						Locale.CHINA);
			}
			String prv = request.getParameter("prv");
			map.put("prv", prv);
			condition.put(InfoAppKeyConstant.K_parameter, map);
			condition.put(InfoAppKeyConstant.K_pageModel, getFliper(request));
			Map<Object, Object> model = roleAction.query(condition);
			PagedFliper page = (PagedFliper) model
					.get(InfoAppKeyConstant.K_pageModel);
			List<Object> data = (List<Object>) model
					.get(InfoAppKeyConstant.K_list);
			Sheet sheet = new Sheet(page.getRecordCount(), data);
			request.setAttribute("message", message);
			return new ModelAndView("role/rolequery", "bean",
					new PagedDataModel(sheet, page, 0));
		} catch (Exception e) {
			logger.error(e);
			return new ModelAndView("error", "bean", "Oops, error occur...");
		}
	}

	/**
	 * 角色添加
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView add(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		MessageSource msg = (MessageSource) this.getApplicationContext()
				.getBean("messageSource");
		try {
			if (logger.isInfoEnabled()) {
				logger.info("调用远程接口: roleAction");
			}
			String roleName = request.getParameter("roleName");
			if (roleName == null || "".equals(roleName)
					|| roleName.length() > 20) {
				return new ModelAndView("error", "bean", msg.getMessage(
						"sys.roleName.error", null, Locale.CHINA));
			}
			String linkId[] = request.getParameterValues("linkId");
			Map<String, Object> condition = new HashMap<String, Object>();
			condition.put("roleName", roleName);
			condition.put("linkId", linkId);
			Map<Object, Object> logMap = this.getLogParaInfo(request);
			logMap.put("ITEM", roleName);
			logMap.put("CLASS", "2");
			logMap.put("NEWMAP", condition);
			condition.put("LOGMAP", logMap);
			Map<Object, Object> model = roleAction.add(condition);
			if (model != null) {
				if (model.get("count") != null
						&& model.get("count").toString().length() > 0
						&& !"".equals(model.get("count").toString())) {
					return new ModelAndView(new RedirectView(
							"role.do?method=query&prv=query"), "message", "2");
				}
			}
			return new ModelAndView(new RedirectView(
					"role.do?method=query&prv=query"), "message", "1");
		} catch (Exception e) {
			logger.error(e);
			return new ModelAndView("error", "bean", "Oops, error occur...");
		}
	}

	/**
	 * 角色修改
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView update(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		MessageSource msg = (MessageSource) this.getApplicationContext()
				.getBean("messageSource");
		try {
			if (logger.isInfoEnabled()) {
				logger.info("调用远程接口: roelAction");
			}
			String roleName = request.getParameter("roleName");
			String roleName1 = request.getParameter("roleName1");
			String linkId[] = request.getParameterValues("linkId");
			String roleId = request.getParameter("roleId");

			if (roleName == null || "".equals(roleName)
					|| roleName.length() > 20) {
				return new ModelAndView("error", "bean", msg.getMessage(
						"sys.roleName.error", null, Locale.CHINA));
			}
			if (roleId == null || "".equals(roleId)) {
				return new ModelAndView("error", "bean", msg.getMessage(
						"sys.roleId.error", null, Locale.CHINA));
			}
			Map<String, Object> condition = new HashMap<String, Object>();
			condition.put("roleName", roleName);
			condition.put("roleName1", roleName1);
			condition.put("linkId", linkId);
			condition.put("roleId", Integer.valueOf(roleId));
			Map<Object, Object> logMap = this.getLogParaInfo(request);
			logMap.put("ITEM", roleName);
			logMap.put("CLASS", "1");
			logMap.put("NEWMAP", condition);
			condition.put("LOGMAP", logMap);
			Map<Object, Object> model = roleAction.update(condition);
			if (model != null && model.get("count") != null
					&& model.get("count").toString().length() > 0
					&& !"".equals(model.get("count").toString())) {
				return new ModelAndView(new RedirectView(
						"role.do?method=query&prv=query"), "message", "2");
			}
			return new ModelAndView(new RedirectView(
					"role.do?method=query&prv=query"), "message", "1");
		} catch (Exception e) {
			logger.error(e);
			return new ModelAndView("error", "bean", "Oops, error occur...");
		}
	}

	/**
	 * 角色删除
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView delete(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		MessageSource msg = (MessageSource) this.getApplicationContext()
				.getBean("messageSource");
		try {
			if (logger.isInfoEnabled()) {
				logger.info("调用远程接口: roleAction");
			}
			String roleId = request.getParameter("id");
			if (roleId == null || "".equals(roleId)) {
				return new ModelAndView(new RedirectView("error"), "bean",
						msg.getMessage("sys.roleId.error", null, Locale.CHINA));
			}
			Map<String, Object> condition = new HashMap<String, Object>();
			condition.put("roleId", Integer.valueOf(roleId));
			Map<Object, Object> logMap = this.getLogParaInfo(request);
			logMap.put("ITEM", roleId);// 操作数据项：这里是游戏名称
			logMap.put("CLASS", "0");// 操作类型
			logMap.put("NEWMAP", condition);
			condition.put("LOGMAP", logMap);
			Map<Object, Object> model = roleAction.delete(condition);
			if (model != null && model.get("error") != null) {
				return new ModelAndView(new RedirectView(
						"role.do?method=query&prv=query"), "message", "3");
			}
			return new ModelAndView(new RedirectView(
					"role.do?method=query&prv=query"), "message", "1");
		} catch (Exception e) {
			logger.error(e);
			return new ModelAndView("error", "bean", "Oops, error occur...");
		}
	}

	/**
	 * 根据角色ID查询角色
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView searchById(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		// 找到本controller在APP中对应的Action.
		MessageSource msg = (MessageSource) this.getApplicationContext()
				.getBean("messageSource");
	
		try {
			if (logger.isInfoEnabled()) {
				logger.info("调用远程接口: roelAction");
			}
			// 获取参数
			String roleId = request.getParameter("id");
			if (roleId == null || "".equals(roleId)) {
				return new ModelAndView("error", "bean", msg.getMessage(
						"sys.roleId.error", null, Locale.CHINA));
			}
			// 组装输入参数
			Map<String, Object> condition = new HashMap<String, Object>();
			condition.put("roleId", Integer.valueOf(roleId));
			Map<Object, Object> model = roleAction.searchById(condition);
			return new ModelAndView("role/roleupdate", "bean", model);
		} catch (Exception e) {
			logger.error(e);
			return new ModelAndView("error", "bean", "Oops, error occur...");
		}
	}

	/**
	 * 为角色添加做准备
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView roleAdd(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		try {
			if (logger.isInfoEnabled()) {
				logger.info("调用远程接口: roelAction");
			}
			Map<String, Object> condition = new HashMap<String, Object>();
			Map<Object, Object> model = roleAction.roleAdd(condition);
			return new ModelAndView("role/roleadd", "bean", model);
		} catch (Exception e) {
			logger.error(e);
			return new ModelAndView("error", "bean", "Oops, error occur...");
		}
	}

	/**
	 * 角色名称是否唯一
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView roleNanme(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		MessageSource msg = (MessageSource) this.getApplicationContext()
				.getBean("messageSource");
		String roleName = request.getParameter("roleName");
		// 组装输入参数
		Map<String, Object> condition = new HashMap<String, Object>();
		condition.put("roleName", roleName);
		try {
			Map<Object, Object> model = roleAction.role(condition);
			StringBuffer str = new StringBuffer();
			response.setContentType("text/html;charset=utf-8");
			PrintWriter out = null;
			out = response.getWriter();
			if (model.get("count") != null
					&& model.get("count").toString().length() > 0
					&& !"".equals(model.get("count").toString())) {
				str.append(msg.getMessage("sys.role.in", null, Locale.CHINA));
			} else {
				str.append("");
			}
			out.print(str.toString());
			out.close();
		} catch (Exception e) {
			logger.error(e);
			return new ModelAndView("error", "bean", "Oops, error occur...");
		}
		return null;
	}

	/**
	 * 角色人员表
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView roleuser(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		MessageSource msg = (MessageSource) this.getApplicationContext()
				.getBean("messageSource");
		
		try {
			if (logger.isInfoEnabled()) {
				logger.info("调用远程接口: roelAction");
			}
			String roleId = request.getParameter("roleId");
			if (roleId == null || "".equals(roleId)) {
				return new ModelAndView("error", "bean", msg.getMessage(
						"sys.roleId.error", null, Locale.CHINA));
			}
			Map<String, Object> condition = new HashMap<String, Object>();
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("roleId", roleId);
			condition.put(InfoAppKeyConstant.K_parameter, map);
			condition.put(InfoAppKeyConstant.K_pageModel, getFliper(request));
			
			Map<Object, Object> model = roleAction.roleUser(condition);
			PagedFliper page = (PagedFliper) model
					.get(InfoAppKeyConstant.K_pageModel);
			List<Object> data = (List<Object>) model
					.get(InfoAppKeyConstant.K_list);
			Sheet sheet = new Sheet(page.getRecordCount(), data);
			request.setAttribute("roleId", roleId);
			return new ModelAndView("role/roleuser", "bean",
					new PagedDataModel(sheet, page, 0));
		} catch (Exception e) {
			logger.error(e);
			return new ModelAndView("error", "bean", "Oops, error occur...");
		}
	}

	/**
	 * 日志IP和工号
	 * 
	 * @param request
	 * @return
	 */
	private Map<Object, Object> getLogParaInfo(HttpServletRequest request) {
		// 写日志用到的信息
		String ip = request.getHeader("x-forwarded-for");
		if ("unknown".equalsIgnoreCase(ip) || ip == null) {
			ip = request.getRemoteAddr();
		}

		Map<Object, Object> userMap = (Map<Object, Object>) request
				.getSession().getAttribute("user");
		if (userMap == null) {
			userMap = new HashMap<Object, Object>();
		}
		Map<Object, Object> returnMap = new HashMap<Object, Object>();
		returnMap.put("OPTIONOR", userMap.get("empno"));
		returnMap.put("IP", ip);

		return returnMap;
	}
}
